package com.iot08.api.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.utils.StringUtils;
import com.iot08.api.config.redis.RedisClusterService;
import com.iot08.api.service.supplement.KafkaService;
import com.iot08.api.vo.request.TimeLimitAppManagerReqVo;
import com.iot08.common.constant.ConstCacheField;
import com.iot08.common.constant.ConstKafka;
import com.iot08.common.entity.app.TimeLimitDeviceAppManager;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author cwj
 * @description App限时禁用
 * @date 2024/11/19 11:40
 **/
@Slf4j
@Service
public class TimeLimitDeviceAppManagerService extends BaseService<TimeLimitDeviceAppManager> {

    @Resource
    private KafkaService kafkaService;

    @Resource
    private RedisClusterService redisClusterService;

    /**
     * @description 查询限时禁用App的设置指令信息
     * @author cwj
     * @param [imei]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2024/11/19 15:33
     **/
    public ResponseMap queryTimeLimitDeviceAppManager(String imei) {
        ResponseMap res = ResponseMap.success();
        Criteria criteria = Criteria.where("imei").is(imei);
        Query query = new Query(criteria).with(Sort.by(Sort.Order.desc("date"))).limit(1);
        TimeLimitDeviceAppManager tldam = this.findOne(query);
        JSONObject data = new JSONObject();
        if(!ObjectUtils.isEmpty(tldam)){
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); // 指定格式
            LocalDateTime localDateTime = tldam.getUpdateDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
            data.put("imei",imei);
            data.put("time1",tldam.getTime1());
            data.put("time1Open",tldam.getTime1Open());
            data.put("time2",tldam.getTime2());
            data.put("time2Open",tldam.getTime2Open());
            data.put("time3",tldam.getTime3());
            data.put("time3Open",tldam.getTime3Open());
            data.put("updateTime",localDateTime.format(formatter));
            res.put("data",data);
        } else {

        }
        return res;
    }


    /**
     * @description 设置限时时间段
     * @author cwj
     * @param [imei, vo]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2024/11/19 11:24
     **/
    public ResponseMap settingTimeLimitDeviceAppManager(String imei, TimeLimitAppManagerReqVo vo){
        String regex = "^([01]?[0-9]|2[0-3]):([0-5][0-9])-([01]?[0-9]|2[0-3]):([0-5][0-9])$";
        //检查参数是否正确
        ResponseMap status410 = checkParam(vo, regex);
        if (status410 != null) return status410;
        setDefaultStatus(vo);
        //检查设备是否在线
        String onlineStatus = redisClusterService.hget(imei, ConstCacheField.ONLINE_STATUS);
        if (!"1".equals(onlineStatus)) {
            return ResponseMap.fail(ResponseEnum.STATUS5001.getCode(), ResponseEnum.STATUS5001.getMsg());
        }
        //一天一条指令记录
        Date date = new Date();
        String todayStr = DateUtil.dateToStr(date, DateUtil.FORMAT_4);
        TimeLimitDeviceAppManager tdam = queryTimeLimitDeviceAppManagerByImeiDate(imei, todayStr);
        if(ObjectUtils.isEmpty(tdam)){
            //组装保存对象
            tdam = assembleTimeLimitDeviceAppManager(imei, vo, todayStr, DateUtil.getDate(date));
            this.save(tdam);
        }else{
            //组装更新对象
            Update update = assembleUpdate(vo, DateUtil.getDate(date));
            this.updateById(tdam.getId(),update);
        }
        //组装发送的指令数据
        JSONObject kafkaJson = assembleKafkaJson(vo);
        //发送限制时间段使用App的指令
        kafkaService.emitDeviceDemand(imei, ConstKafka.DEVICE_TYPE_SETAPPFN_TIMEOR_DISABLE, kafkaJson, vo.getOpenid());
        return ResponseMap.success();
    }

    /**
     * @description 组装推送kafka数据的内容
     * @author cwj
     * @param [vo]
     * @return com.alibaba.fastjson.JSONObject
     * @date @time 2024/11/19 14:55
     **/
    private static JSONObject assembleKafkaJson(TimeLimitAppManagerReqVo vo) {
        JSONObject kafkaJson = new JSONObject();
        kafkaJson.put("time1", vo.getTime1());
        kafkaJson.put("time1Open", vo.getTime1Open());
        kafkaJson.put("time2", vo.getTime2());
        kafkaJson.put("time2Open", vo.getTime2Open());
        kafkaJson.put("time3", vo.getTime3());
        kafkaJson.put("time3Open", vo.getTime3Open());
        return kafkaJson;
    }

    /**
     * @description 组装更新数据的对象
     * @author cwj
     * @param [vo, date]
     * @return org.springframework.data.mongodb.core.query.Update
     * @date @time 2024/11/19 14:37
     **/
    private Update assembleUpdate(TimeLimitAppManagerReqVo vo, Date date) {
        Update update = new Update();
        update.set("openId", vo.getOpenid());
        update.set("time1", vo.getTime1());
        update.set("time1Open", vo.getTime1Open());
        update.set("time2", vo.getTime2());
        update.set("time2Open", vo.getTime2Open());
        update.set("time3", vo.getTime3());
        update.set("time3Open", vo.getTime3Open());
        update.set("updateDate", date);
        return update;
    }

    /**
     * @description 组装限制App时段的指令数据
     * @author cwj
     * @param [imei, vo, todayStr, date]
     * @return com.iot08.common.entity.app.TimeLimitDeviceAppManager
     * @date @time 2024/11/19 14:27
     **/
    private static TimeLimitDeviceAppManager assembleTimeLimitDeviceAppManager(String imei, TimeLimitAppManagerReqVo vo, String todayStr, Date date) {
        TimeLimitDeviceAppManager tdam;
        tdam = new TimeLimitDeviceAppManager();
        tdam.setImei(imei);
        tdam.setDate(todayStr);
        tdam.setCreateDate(date);
        tdam.setUpdateDate(date);
        tdam.setOpenId(vo.getOpenid());
        tdam.setTime1(vo.getTime1());
        tdam.setTime2(vo.getTime2());
        tdam.setTime3(vo.getTime3());
        tdam.setTime1Open(vo.getTime1Open());
        tdam.setTime2Open(vo.getTime2Open());
        tdam.setTime3Open(vo.getTime3Open());
        return tdam;
    }

    /**
     * @description 设置默认的限制时段开关
     * @author cwj
     * @param [vo]
     * @return void
     * @date @time 2024/11/19 14:21
     **/
    private void setDefaultStatus(TimeLimitAppManagerReqVo vo) {
        if(StringUtils.isEmpty(vo.getTime1())){
            vo.setTime1("");
            vo.setTime1Open("0");
        }
        if(StringUtils.isEmpty(vo.getTime2())){
            vo.setTime2("");
            vo.setTime2Open("0");
        }
        if(StringUtils.isEmpty(vo.getTime3())){
            vo.setTime3("");
            vo.setTime3Open("0");
        }
    }

    /**
     * @description 检查参数是否正确
     * @author cwj
     * @param [vo, regex]
     * @return com.iot08.common.utils.response.ResponseMap
     * @date @time 2024/11/19 14:11
     **/
    private ResponseMap checkParam(TimeLimitAppManagerReqVo vo, String regex) {
        if(StringUtils.isEmpty(vo.getTime1()) && StringUtils.isEmpty(vo.getTime2()) && StringUtils.isEmpty(vo.getTime2())) {
            return ResponseMap.fail(ResponseEnum.STATUS410.getCode(), "API.request.parameterError.TimeLimitDevAppManager.all.empty");
        }
        if(!StringUtils.isEmpty(vo.getTime1()) && StringUtils.isEmpty(vo.getTime1Open())){
            return ResponseMap.fail(ResponseEnum.STATUS410.getCode(), "API.request.parameterError.TimeLimitDevAppManager.time1.status");
        }
        if(!StringUtils.isEmpty(vo.getTime1()) && !vo.getTime1().matches(regex)){
            return ResponseMap.fail(ResponseEnum.STATUS410.getCode(), "API.request.parameterError.TimeLimitDevAppManager.time1.formatter");
        }
        if(!StringUtils.isEmpty(vo.getTime2()) && StringUtils.isEmpty(vo.getTime2Open())){
            return ResponseMap.fail(ResponseEnum.STATUS410.getCode(), "API.request.parameterError.TimeLimitDevAppManager.time2.status");
        }
        if(!StringUtils.isEmpty(vo.getTime2()) && !vo.getTime2().matches(regex)){
            return ResponseMap.fail(ResponseEnum.STATUS410.getCode(), "API.request.parameterError.TimeLimitDevAppManager.time2.formatter");
        }
        if(!StringUtils.isEmpty(vo.getTime3()) && StringUtils.isEmpty(vo.getTime3Open())){
            return ResponseMap.fail(ResponseEnum.STATUS410.getCode(), "API.request.parameterError.TimeLimitDevAppManager.time3.status");
        }
        if(!StringUtils.isEmpty(vo.getTime3()) && !vo.getTime3().matches(regex)){
            return ResponseMap.fail(ResponseEnum.STATUS410.getCode(), "API.request.parameterError.TimeLimitDevAppManager.time3.formatter");
        }
        return null;
    }

    /**
     * @description 查询当天的限制App使用时间段记录
     * @author cwj
     * @param [imei, todayStr]
     * @return com.iot08.common.entity.app.TimeLimitDeviceAppManager
     * @date @time 2024/11/19 14:14
     **/
    private TimeLimitDeviceAppManager queryTimeLimitDeviceAppManagerByImeiDate(String imei, String todayStr) {
        Query query = new Query(Criteria.where("imei").is(imei).and("date").is(todayStr));
        TimeLimitDeviceAppManager tdam= this.findOne(query);
        return tdam;
    }
}
